package inc.monsters.mias.data.facade;

import inc.monsters.mias.data.Kid;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class KidService
 */
//@Stateless(name="mias/KidService", mappedName="mias/KidService")
//@TransactionManagement(TransactionManagementType.BEAN)
//@Remote
public class KidServiceBean implements KidService {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");
	
	@PersistenceContext
	private EntityManager em;

    /**
     * Default constructor. 
     */
    public KidServiceBean() {
    }

	@SuppressWarnings("unchecked")
	@Override
	public List<Kid> getKids() {
    	Query q = em.createNamedQuery("Kid.all");
    	return q.getResultList();
	}

	@Override
	public boolean existsKid(Kid k) {
		if(null == em.find(Kid.class, k.getId())) {
			return false;
		} else {
			return true;
		}
	}
	
	@Override
	public void updateKid(Kid k) {
		log.fine("Merging kid with ID " + k.getId() + "...");
		if(null == em.find(Kid.class, k.getId())) {
			throw new IllegalArgumentException("Unknown kid id: " + k.getId());
		}
		
        try {
    		em.merge(k);
        } catch (RuntimeException e) {
        	log.warning("Merging of kid with id " + k.getId() + " failed: " + e.getClass() + ": " + e.getMessage());
            throw e;
        } 	
    }

	@Override
	public void addKid(Kid k) {
		log.fine("Adding new kid:" + k);
        try {
    		em.persist(k);
        } catch (RuntimeException e) {
        	log.warning("Persist of kid with id " + k.getId() + " failed: " + e.getClass() + ": " + e.getMessage());
            throw e;
        } 	
	}
	
	@Override
	public void deleteKid(Kid k) {
        try {
    		// We cannot call remove with k, because this is a detached object.
        	// Instead we call find() to get the managed object with the same ID.
        	Kid d = em.find(Kid.class, k.getId());
        	if (d != null) {
        		em.remove(d);
        	} else {
        		throw new IllegalArgumentException("Unknown kid id: " + k.getId());
        	}
        } catch (RuntimeException e) {
        	log.warning("Remove of kid with id " + k.getId() + " failed: " + e.getClass() + ": " + e.getMessage());
            throw e;
        } 		
	}

	@Override
	public Kid getKidById(int id) {
    	return em.find(Kid.class, id);
	}
}